package com.vict.util;



import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;

@Slf4j
public class TimeUtil {

    public static final long day_msec = 24L * 60L * 60L * 1000L;
    public static final long week_msec = 7L * 24L * 60L * 60L * 1000L;
    public static LocalDateTime convert(Long timestamp){
        return new Date(timestamp).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
    }
    public static Long convert(LocalDateTime time){
        return Date.from(time.toInstant(ZoneOffset.of("+8"))).getTime();
    }

    public static Long getTime(String format, String time){
        try {
            return new SimpleDateFormat(format).parse(time).getTime();
        } catch (ParseException e) {
            throw new RuntimeException("格式化时间异常");
        }
    }

    public static String getTimeStr(String format, Long time){
        if(format == null){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        if(time == null){
            time = System.currentTimeMillis();
        }
        return new SimpleDateFormat(format).format(time);
    }
    public static String getTimeStr(Long time){
        if(time == null){
            time = System.currentTimeMillis();
        }
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);
    }

    public static Long getTime(String timeStr){
        if(timeStr == null || timeStr.trim().equals("")){
            return null;
        }
        if(timeStr.trim().matches("\\d+")){
            return Long.parseLong(timeStr.trim());
        }else{
            try{
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date parse = simpleDateFormat.parse(timeStr);
                return parse.getTime();
            }catch(Exception e){
                log.error("日期格式不正确" + timeStr);
            }
        }
        return null;
    }

}
